<?php

namespace App\Http\Controllers;

use App\Services\PaymentService;
use EasyWeChat\Factory;

class CallbackController extends Controller
{
    protected $paymentService;
    public function __construct(){
        $this->paymentService = new PaymentService();
        InterfaceLog('', '支付回调日志1');
    }

    /**
     * 购买vip订单回调
     * @return string
     */
    public function vipCallback()
    {
        $config = config('wechat.payment.default');
        $app = Factory::payment($config);
        $response = $app->handlePaidNotify(function($message, $fail){
            callbackLog($message, '支付回调日志');
            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                if (array_get($message, 'result_code') === 'SUCCESS') {
                    $re = $this->paymentService->openVipResult($message['out_trade_no'], 1, $message['transaction_id']);
                } elseif (array_get($message, 'result_code') === 'FAIL') {
                    // 用户支付失败
                    $re = $this->paymentService->openVipResult($message['out_trade_no'], 0, $message['transaction_id']);
                }
                if( $re ){
                    return true; // 返回处理完成
                }
                return $fail('通信失败，请稍后再通知我');
            } else {
                return $fail('通信失败，请稍后再通知我');
            }
            
        });
        
        $response->send(); // return $response;
    }

    /**
     * 结算订单回调
     * @return string
     */
    public function settleCallback()
    {
        $config = config('wechat.payment.default');
        $app = Factory::payment($config);
        $response = $app->handlePaidNotify(function($message, $fail){
            callbackLog($message, '支付回调日志');
            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                if (array_get($message, 'result_code') === 'SUCCESS') {
                    $re = $this->paymentService->settleResult($message['out_trade_no'], 1, $message['transaction_id']);
                } elseif (array_get($message, 'result_code') === 'FAIL') {
                    // 用户支付失败
                    $re = $this->paymentService->settleResult($message['out_trade_no'], 0, $message['transaction_id']);
                }
                if( $re ){
                    return true; // 返回处理完成
                }
                return $fail('通信失败，请稍后再通知我');
            } else {
                return $fail('通信失败，请稍后再通知我');
            }
            
        });
        
        $response->send(); // return $response;
    }
}
